package com.Cfeng.XiaohuanChat.controller;

import com.Cfeng.XiaohuanChat.domain.Resp;
import com.Cfeng.XiaohuanChat.entity.ChatUser;
import com.Cfeng.XiaohuanChat.entity.UserNote;
import com.Cfeng.XiaohuanChat.service.ChatUserService;
import com.Cfeng.XiaohuanChat.service.UserNoteService;
import com.mysql.cj.util.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author Cfeng
 * @date 2022/8/13
 * 登录用户的个人笔记处理器，包括基本的CRUD和其他功能
 * 该处理器完全使用Restful风格处理
 */

@RestController
@RequiredArgsConstructor
@RequestMapping("/note")
@Slf4j
public class UserNoteController {

    private final UserNoteService userNoteService;

    private final ChatUserService userService;

    @PostMapping("/")
    //当前登录用户新增一篇笔记
    public Resp<String> addNote(UserNote userNote, Principal principal) {
        if(StringUtils.isNullOrEmpty(userNote.getNoteTitle()) || StringUtils.isNullOrEmpty(userNote.getNoteContent()) || StringUtils.isNullOrEmpty(userNote.getNoteDescription())) {
            return Resp.failed("Error！上传的笔记不能为空");
        }
        //接收之后就设置创建时间为now
        userNote.setNoteCreateTime(LocalDateTime.now());
        //创建关联关系
        ChatUser user = userService.queryUser(principal.getName());
        user.getUserNoteList().add(userNote);
        userNote.setUser(user);
        //持久化
        userNoteService.addNote(userNote);
        return Resp.ok("上传笔记成功");
    }

    @GetMapping("/{noteId}")
    public ModelAndView queryNote(@PathVariable("noteId") Long id) {
        ModelAndView modelAndView = new ModelAndView();
        UserNote userNote = userNoteService.getNote(id);
        if(Objects.isNull(userNote)) {
            throw new RuntimeException("此文章不存在,请重试");
        }
        ChatUser chatUser = userNote.getUser();
        chatUser.setUserHeaderImg("/" + chatUser.getUserHeaderImg());
        modelAndView.addObject("chatUser", chatUser);
        modelAndView.addObject("noteNumber",chatUser.getUserNoteList().size());
        modelAndView.addObject("note",userNote);
        modelAndView.setViewName("noteDetail");
        return modelAndView;
    }

    /**
     * 前台AJAX发起请求类型POST，data中设置_method参数为delete即可实现
     */
    @DeleteMapping("/{title}")
    public Resp<String> deleteNote(@PathVariable String title) {
        System.out.println(title);
        userNoteService.removeNote(title);
        return Resp.ok("删除成功");
    }

    @PutMapping("/")
    public Resp<String> updateNote(UserNote userNote) throws Exception {
        log.info("更新数据：" + userNote.toString());
        userNoteService.updateNote(userNote);
        return Resp.ok("更新成功");
    }

}
